package com.yang.service.Impl;

import com.alibaba.fastjson.JSON;
import com.yang.mapper.AddressMapper;
import com.yang.entity.Address;
import com.yang.service.AddressService;
import com.yang.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    @Transactional
    public void addAddress(Address address) {
        // 新增地址信息
        addressMapper.addAddress(address);
        // 更新redis中用户收货地址缓存
        updateAddressRedis(address.getUserId());
    }

    @Override
    public int userAddressCount(Integer userId) {
        // 查询用户地址数量
        List<Address> addressList = addressMapper.getAddressList(userId);
        return addressList.size();
    }

    @Override
    @Transactional
    public void deleteAddress(Integer userId, Integer addressId) {
        // 根据用户id和地址id删除地址信息
        addressMapper.deleteAddress(userId, addressId);
        // 更新redis中用户收货地址缓存
        updateAddressRedis(userId);
    }

    @Override
    public void updateAddress(Address address) {
        // 更新地址信息
        addressMapper.updateAddress(address);
        // 更新redis中用户收货地址缓存
        updateAddressRedis(address.getUserId());
    }

    @Override
    public List<Address> getAddressList() {
        // 结果集
        List<Address> addressList = null;
        // 获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        int userId = (int) map.get("userId");
        // key值
        String key = "user_" + userId;
        // 从redis中获取收货地址列表
        String addressJson = (String) redisTemplate.opsForHash().get(key, "address");
        if(addressJson == null) {
            // 从数据库中获取收货地址列表
            addressList = updateAddressRedis(userId);
        }else{
            // 解析json字符串
            addressList = JSON.parseArray(addressJson).toJavaList(Address.class);
        }
        // 根据用户id查询地址列表
        return addressList;
    }

    // 更新redis中用户收货地址缓存
    private List<Address> updateAddressRedis(long userId){
        // key值
        String key = "user_" + userId;
        // 从数据库中获取收货地址列表
        List<Address> addressList = addressMapper.getAddressList(userId);
        String subListJson = JSON.toJSONString(addressList);
        redisTemplate.opsForHash().putAll(key, Collections.singletonMap("address", subListJson));
        redisTemplate.expire(key, 12, TimeUnit.HOURS);
        // 返回收货地址列表
        return addressList;
    }
}
